package com.yami.shop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private EmailService emailService;

    /**
     * 生成验证码并发送到邮箱
     */
    public void sendVerificationCode(String email) {
        // 生成 6 位随机验证码
        String verificationCode = generateVerificationCode();

        // 将验证码存储到 Redis，设置过期时间为 5 分钟
        redisTemplate.opsForValue().set(email, verificationCode, 5, TimeUnit.MINUTES);

        // 发送验证码到邮箱
        emailService.sendVerificationCode(email, verificationCode);
    }

    /**
     * 验证用户输入的验证码
     */
    public boolean verifyCode(String email, String code) {
        // 从 Redis 中获取验证码
        String storedCode = redisTemplate.opsForValue().get(email);

        // 比较用户输入的验证码和存储的验证码
        return code != null && code.equals(storedCode);
    }

    /**
     * 生成 6 位随机验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}